package com.xxl.vueadmin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxl.vueadmin.common.Result;
import com.xxl.vueadmin.entity.SysRole;
import com.xxl.vueadmin.entity.SysRoleMenu;
import com.xxl.vueadmin.entity.SysUserRole;
import com.xxl.vueadmin.service.ISysRoleMenuService;
import com.xxl.vueadmin.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  角色前端控制器
 * </p>
 *
 * @author xu
 * @since 2021-07-28
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {
    @Autowired
    ISysRoleMenuService roleMenuService;

    @Autowired
    ISysUserRoleService userRoleService;

    @GetMapping("info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:role:list')")
    public Result getRoleInfo(@PathVariable String id) {
        SysRole role = sysRoleService.getById(id);
        List<SysRoleMenu> roleMenuList = roleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", role.getId()));
        List<String> menuIdList = roleMenuList.stream().map(roleMenu -> roleMenu.getMenuId()).collect(Collectors.toList());
        role.setMenuIds(menuIdList);
        return  Result.success(role);
    }

    @GetMapping("list")
    @PreAuthorize("hasAnyAuthority('sys:role:list')")
    public Result getPage( String name) {
        Page<SysRole> pageData = sysRoleService.page(getPage(),
                                         new QueryWrapper<SysRole>().like(StringUtils.isNotBlank(name),
                                 "name", name));
        return  Result.success(pageData);
    }

    @PostMapping("save")
    @PreAuthorize("hasAnyAuthority('sys:role:save')")
    public Result saveRole(@Validated @RequestBody SysRole sysRole) {
         sysRoleService.save(sysRole);
         return  Result.success("添加成功");
    }

    @PostMapping("edit")
    @PreAuthorize("hasAnyAuthority('sys:role:update')")
    public Result editRole(@Validated @RequestBody SysRole sysRole) {
        sysRoleService.updateById(sysRole);
        sysUserService.clearRoleAuthority(sysRole.getId());
        return Result.success("修改成功");
    }

    @DeleteMapping("remove")
    @PreAuthorize("hasAnyAuthority('sys:role:delete')")
    @Transactional(rollbackFor = RuntimeException.class)
    public Result remove(@RequestBody String[] roleIds){
        List<String> rids = Stream.of(roleIds).collect(Collectors.toList());
        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id", rids));
        userRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id", rids));
        sysRoleService.removeByIds(rids);
        rids.forEach(rid -> {
            sysUserService.clearRoleAuthority(rid);
        });
        return Result.success("删除成功");
    }

    @PostMapping("prem/{roleId}")
    @PreAuthorize("hasAnyAuthority('sys:role:perm')")
    public Result prem(@PathVariable String roleId,@RequestBody String[] menuIds) {
        roleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        List<SysRoleMenu> permList = Stream.of(menuIds)
                .map(menuId -> {
                    SysRoleMenu sysRoleMenu = new SysRoleMenu();
                    sysRoleMenu.setMenuId(menuId);
                    sysRoleMenu.setRoleId(roleId);
                    return sysRoleMenu;
                })
                .collect(Collectors.toList());
        roleMenuService.saveBatch(permList);
        sysUserService.clearRoleAuthority(roleId);
        return  Result.success(permList);
    }

}
